package com.svconnect.util;

public final class Base64Encoder {

	private static final char[] map = new char[64];

	private static final byte[] inverseMap = new byte[128];

	static {

		int i = 0;
		for (char c = 'A'; c <= 'Z'; c++) {
			map[i++] = c;
		}
		for (char c = 'a'; c <= 'z'; c++) {
			map[i++] = c;
		}
		for (char c = '0'; c <= '9'; c++) {
			map[i++] = c;
		}
		map[i++] = '+';
		map[i++] = '/';

		for (i = 0; i < inverseMap.length; i++) {
			inverseMap[i] = -1;
		}
		for (i = 0; i < 64; i++) {
			inverseMap[map[i]] = (byte) i;
		}
	}

	private Base64Encoder() {
		super();
	}

	public static char[] encode(byte[] input) {
		return encode(input, input.length);
	}

	public static char[] encode(byte[] input, int inputSize) {
		int oDataLen = (inputSize * 4 + 2) / 3;
		int oLen = ((inputSize + 2) / 3) * 4;
		char[] out = new char[oLen];
		int ip = 0;
		int op = 0;
		while (ip < inputSize) {
			int i0 = input[ip++] & 0xff;
			int i1 = ip < inputSize ? input[ip++] & 0xff : 0;
			int i2 = ip < inputSize ? input[ip++] & 0xff : 0;
			int o0 = i0 >>> 2;
			int o1 = ((i0 & 3) << 4) | (i1 >>> 4);
			int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
			int o3 = i2 & 0x3F;
			out[op++] = map[o0];
			out[op++] = map[o1];
			out[op] = op < oDataLen ? map[o2] : '=';
			op++;
			out[op] = op < oDataLen ? map[o3] : '=';
			op++;
		}
		return out;
	}

	public static String encodeString(String input) {
		return new String(encode(input.getBytes()));
	}

	public static byte[] decode(char[] input) {
		int iLen = input.length;
		if (iLen % 4 != 0) {
			throw new IllegalArgumentException(
					"Length of Base64 encoded input string is not a multiple of 4.");
		}
		while (iLen > 0 && input[iLen - 1] == '=') {
			iLen--;
		}
		int oLen = (iLen * 3) / 4;
		byte[] out = new byte[oLen];
		int ip = 0;
		int op = 0;
		while (ip < iLen) {
			int i0 = input[ip++];
			int i1 = input[ip++];
			int i2 = ip < iLen ? input[ip++] : 'A';
			int i3 = ip < iLen ? input[ip++] : 'A';
			if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) {
				throw new IllegalArgumentException(
						"Illegal character in Base64 encoded data.");
			}
			int b0 = inverseMap[i0];
			int b1 = inverseMap[i1];
			int b2 = inverseMap[i2];
			int b3 = inverseMap[i3];
			if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) {
				throw new IllegalArgumentException(
						"Illegal character in Base64 encoded data.");
			}
			int o0 = (b0 << 2) | (b1 >>> 4);
			int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2);
			int o2 = ((b2 & 3) << 6) | b3;
			out[op++] = (byte) o0;
			if (op < oLen) {
				out[op++] = (byte) o1;
			}
			if (op < oLen) {
				out[op++] = (byte) o2;
			}
		}
		return out;
	}

	public static byte[] decode(String input) {
		return decode(input.toCharArray());
	}

	public static String decodeString(String input) {
		return new String(decode(input));
	}
}
